import React from 'react'
import withLayout from '../components/Layout'
import axios from 'axios'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
class PlotChart extends React.Component {
  render() {
    const { data } = this.props
    let min = Infinity, max = 0
    data.forEach(item => {
      if (item.y < Number(min)) {
        min = item.y
      }
      if (item.y > Number(max)) {
        max = item.y
      }
    })

    return (
      <div>
        <BarChart width={4000} height={600} data={data}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="title" />
          <YAxis />
          <Tooltip />
          <Legend />
          <Bar dataKey="minPrice" stackId="a" fill="#8884d8" />
          {/* <Bar dataKey="maxPrice" stackId="b" fill="#82ca9d" /> */}
        </BarChart>
      </div>
    );
  }
}

class Price extends React.Component {
  $map = React.createRef()
  map = null
  state = {
    list: [],
    pageNumber: 1,
    pageCount: 300,
    total: 0,
  }

  async componentDidMount() {
    await this.fetch()
  }

  fetch = async () => {
    const params = {
      pageNumber: this.state.pageNumber,
      pageCount: this.state.pageCount
    }
    const data = await axios.get('/houses', { params })
    const { list, pageNumber, pageCount, sum } = data
    this.setState({ list, pageNumber, pageCount, sum })
    return Promise.resolve(data)
  }

  get data() {
    const data = this.state.list
      .map((item, index) => {
        const title = item.title.length > 15 ? item.title.substr(0, 15) + '...' : item.title
        const minPrice = Number(item.prices[0] || 0)
        const maxPrice = Number(item.prices[1] || minPrice)
        return { title, minPrice, maxPrice }
      })
      .sort((a, b) => a.minPrice - b.minPrice)
      .filter(item => item.minPrice)

    return data
  }

  render() {
    return (
      <div className="do-common-container" style={{ maxWidth: 1200, overflowX: 'auto' }}>
        <div className="price-chart-wrapper">
          <PlotChart data={this.data} range={[0, 40000]} />
        </div>
      </div>
    )
  }
}

export default withLayout(Price)